package org.jash.learnmvp.chat;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMContact;
import com.hyphenate.exceptions.HyphenateException;


import org.jash.learnmvp.R;

import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;


public class GroupFragment extends Fragment {
    private RecyclerView recycler;
    private ContactAdapter adapter;
    public GroupFragment() {
        super(R.layout.fragment_group);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recycler = view.findViewById(R.id.recycler);
        adapter = new ContactAdapter();
        recycler.setAdapter(adapter);
        adapter.setListener(contact -> requireContext().startActivity(new Intent(requireContext(), ChatDetailActivity.class){{
            putExtra("username", contact.getUsername());
        }}));
        Disposable disposable = Observable.create(new ObservableOnSubscribe<List<EMContact>>() {
                    @Override
                    public void subscribe(@io.reactivex.rxjava3.annotations.NonNull ObservableEmitter<List<EMContact>> emitter) throws Throwable {
                            EMClient.getInstance().contactManager().asyncFetchAllContactsFromServer(new EMValueCallBack<List<EMContact>>() {
                                @Override
                                public void onSuccess(List<EMContact> emContacts) {
                                    emitter.onNext(emContacts);
                                    emitter.onComplete();
                                }

                                @Override
                                public void onError(int i, String s) {
                                    emitter.onError(new HyphenateException(i, s));
                                }
                            });
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(adapter::addAll, t -> {
                    Toast.makeText(requireContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
                });

    }
}